#![allow(non_snake_case)]
use leptos::prelude::*;
use shq_web_controls::MultiTreeSelect;
use std::vec::Vec;

// 导入服务器函数
use crate::utils::{get_user_menus, server_functions::{fetch_top_menus}};

#[component]
pub fn UserMenuComponent(
    sel_user_id: ReadSignal<Option<u32>>,
    selected_menu_ids: RwSignal<Vec<String>>,
) -> impl IntoView {
    // 获取菜单数据
    let menu_items = Resource::new(move || (), |_| async { fetch_top_menus().await });
    let user_menus = LocalResource::new(move || {
        let id = sel_user_id.get();
        async move {
            if let Some(user_id) = id {
                get_user_menus(user_id).await
            } else {
                Ok(vec![])
            }
        }
    });
    let sel_menu_ids = Memo::new(move |_| {
        let sel_menu_ids: Vec<String> = user_menus.get().as_deref().cloned()
            .iter()
            .flat_map(|menu_id_result| match menu_id_result {
                Ok(menu_ids) => menu_ids.iter()
                    .map(|id| {
                        // 处理转义引号，移除多余的引号
                        let s = format!("{:?}", id);
                        s.trim_matches('"').to_string()
                    })
                    .collect::<Vec<String>>(),
                Err(_) => vec![],
            })
            .collect();
        sel_menu_ids
    });
    let on_change = move |values: Vec<String>| {
        // if let Some(Ok(role_menu_ids)) = role_menus.get() {
        //     // 将 role_menus 中的所有值与 values 合并
        //     let mut combined_values: Vec<String> = role_menu_ids.iter()
        //         .map(|id| {
        //             // 处理转义引号，移除多余的引号
        //             let s = format!("{:?}", id);
        //             s.trim_matches('"').to_string()
        //         })
        //         .collect();
        //     let mut seen_values: std::collections::HashSet<String> = combined_values.iter().cloned().collect();
        //     combined_values.extend(values.into_iter().filter(|value| seen_values.insert(value.clone())));
        //     selected_menu_ids.set(combined_values);
        // } else {
        //     // 如果 role_menus 还没有加载完成，直接设置为新的 values
        //     selected_menu_ids.set(values);
        // }
        selected_menu_ids.set(values);
    };
    view! {
        <div class="bg-white shadow rounded-lg p-4 flex-1 flex flex-col min-h-1">
            <h1 class="text-xl font-bold mb-4">功能菜单</h1>
            <Suspense fallback=|| view! { <progress class="progress w-56"></progress> }>
                {move || match menu_items.get() {
                    Some(Ok(menus)) => {
                        let tree_items = StoredValue::new(menus.into());
                        view! {
                            <div class="flex-1 overflow-y-auto min-h-1">
                                <MultiTreeSelect
                                    tree_items
                                    show_confirm_cancel_btn=false
                                    on_change
                                    values = sel_menu_ids.get()
                                />
                            </div>
                        }.into_any()
                    }
                    Some(Err(e)) => {
                        view! {
                            <div class="p-4 text-red-500">
                                {e.to_string()}
                            </div>
                        }.into_any()
                    }
                    None => {
                        view! {
                            <div class="flex-1 flex items-center justify-center">
                                "正在加载菜单数据..."
                            </div>
                        }.into_any()
                    }
                }}
            </Suspense>
        </div>
    }
    .into_any()
}
